﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SmartSiteManagementSystem.AdminWeb.Extensions;
using SmartSiteManagementSystem.AdminWeb.Filter;
using SmartSiteManagementSystem.AdminWeb.Models;
using SmartSiteManagementSystem.IServices;
using SmartSiteManagementSystem.Models.User;
using SmartSiteManagementSystem.Models.DTO;
using System.Collections;
using SmartSiteManagementSystem.Models.Enums;
using SmartSiteManagementSystem.Utils;
using SmartSiteManagementSystem.Models.GeneticProgram;

namespace SmartSiteManagementSystem.AdminWeb.Controllers
{

  
    public class UserController : AdminBaseControllers
    {

        private readonly ILogger<UserController> _logger;

        //注入后台服务
        private readonly IAdminService _adminService;
        private readonly IUserService _userService;
        public UserController(IAdminService adminService, IUserService userService,  ILogger<UserController> logger) : base(adminService)
        {
            _logger = logger;
            _adminService = adminService;
            _userService = userService;
        }


        /// <summary>
        ///  物料首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="name"></param>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        public JsonResult GetList(string name, int page = 0, int rows = 50)
        {
            if (page < 1)
            {
                page = 1;
            }
            page = (page - 1) * rows;

            Hashtable param = new Hashtable();
            param.Add("is_delete", 0);//正常 0 false
            //if (catagoryId > 0)
            //    param.Add("catalog_id", catagoryId);
            int count = _userService.GetUserInfoListCount(param);
            IList<UserInfo> list = _userService.GetUserInfoList(param, "", page, rows);
            var data = new
            {
                total = count,
                rows = list
            };
            return Json(data);
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="userId"></param>
        public JsonResult ajaxUpdateUserState(int userId)
        {
            UserInfo userInfo = null;
            ResultInfo result = new ResultInfo();
            result.IsSuccess = false;
            result.Code = 200;
            result.Msg = "操作失败!";
            if (userId > 0)
            {
                userInfo = _userService.GetUserInfoById(userId);
                userInfo.IsStop = userInfo.IsStop ? false : true;
                result.IsSuccess = _userService.UpdateUserInfo(userInfo);

            }
            if (result.IsSuccess)
            {
                result.Msg = "操作成功!";
            }
            return Json(result);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="userId"></param>
        public JsonResult ajaxDeleteUser(int userId)
        {
            ResultInfo result = new ResultInfo();
            result.IsSuccess = false;
            result.Code = 200;
            result.Msg = "操作失败!";
            if (userId > 0)
            {
                UserInfo userInfo = _userService.GetUserInfoById(userId);
                if (userInfo != null)
                {
                    userInfo.IsDelete = true;
                    result.IsSuccess = _userService.UpdateUserInfo(userInfo);
                }
            }
            if (result.IsSuccess)
            {
                result.Msg = "成功删除!";
            }
            return Json(result);
        }



        /// <summary>
        /// 添加或修改
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public ActionResult Access(int userId = 0)
        {
            UserInfo userInfo = new UserInfo();
            if (userId > 0)
            {
                userInfo = _userService.GetUserInfoById(userId);
            }
            ViewBag.userInfo = userInfo;

            return View();
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="LogonName"></param>
        /// <param name="PositionType"></param>
        /// <param name="ShowName"></param>
        /// <param name="Sex"></param>
        /// <param name="Email"></param>
        /// <param name="Mobile"></param>
        public JsonResult ajaxAccess(int UserId, string LogonName,int PositionType,string ShowName, int Sex, string Email, string Mobile)
        {
            ResultInfo result = new ResultInfo();
            result.IsSuccess = false;
            result.Code = 0;
            result.Msg = "操作失败!";
            UserInfo userInfo =  null;
            bool success = false;
            int code = -1;
            if (UserId > 0)
            {
                userInfo = _userService.GetUserInfoById(UserId);
            }
            else
            {



                userInfo = new UserInfo();
                userInfo.LogonName = LogonName;
                userInfo.LogonPwd = EncryptionUtils.GetUserLoginPwd_SHA1(LogonName, "666666");
                userInfo.IsStop = false;
                userInfo.CreateTime = DateTime.Now;
                //userInfo.LastestLogonIp =
                userInfo.RegType = (int)EUserRegLogonNameType.中台注册;
                userInfo.LastestLogonTime = DateTime.Now;
            }
            userInfo.IsDelete = false;
            userInfo.PositionType = PositionType;
            userInfo.Mobile = Mobile;
            userInfo.Email = Email;
            userInfo.Sex = (short)Sex;
            userInfo.ShowName = ShowName;

            if (UserId > 0)
            {
               
                success = _userService.UpdateUserInfo(userInfo);
                if (success)
                {
                    code = 1;
                }
            }
            else
            {
                if (_userService.GetUserInfoByLogin(LogonName) == null)
                {

                    UserId = _userService.InsertUserInfo(userInfo);
                    success = UserId > 0 ? true : false;
                    if (success)
                    {
                        code = 1;
                    }
                }
                else
                {
                    code = -2;
                }
            }
            if (code == 1)
            {
                result.IsSuccess = true;
                result.Msg = "操作成功!";
            }
            result.Code = code;
            return Json(result);
        }

        #region 健康监测

        /// <summary>
        ///  健康监测首页
        /// </summary>
        /// <returns></returns>
        public ActionResult HealthMonitorIndex()
        {
            Hashtable uparam = new Hashtable();
            uparam.Add("is_delete", 0);//正常 0 false
            IList<UserInfo> userList = _userService.GetUserInfoList(uparam, "", 0, 500);

            ViewBag.userList = userList;

            return View();
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        public JsonResult GetHealthMonitorList(int userId, string searchKey, int page = 0, int rows = 50)
        {
            if (page < 1)
            {
                page = 1;
            }
            page = (page - 1) * rows;
            Hashtable param = new Hashtable();
            if (userId > 0)
                param.Add("user_id", userId);
            int count = _userService.GetHealthMonitorListCount(param);
            IList<UserHealthMonitorInfo> list = _userService.GetHealthMonitorList(param, "", page, rows);
            foreach (UserHealthMonitorInfo item in list)
            {
                UserInfo itemUser = _userService.GetUserInfoById(item.UserId);
                if (itemUser != null)
                {
                    item.UserName = itemUser.LogonName;
                }

            }
            var data = new
            {
                total = count,
                rows = list
            };
            return Json(data);

        }


        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="logId"></param>
        public JsonResult ajaxDeleteUserHealthMonitor(int logId)
        {
            ResultInfo result = new ResultInfo();
            result.IsSuccess = false;
            result.Code = 200;
            result.Msg = "操作失败!";
            if (logId > 0)
            {
                UserHealthMonitorInfo info = _userService.GetUserHealthMonitorInfoById(logId);
                if (info != null)
                {

                    result.IsSuccess = _userService.DeleteUserHealthMonitorInfoById(logId);
                }
            }
            if (result.IsSuccess)
            {
                result.Msg = "成功删除!";
            }
            return Json(result);
        }



        /// <summary>
        /// 添加或修改
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult UserHealthMonitorAccess(int id = 0)
        {
            UserHealthMonitorInfo info = new UserHealthMonitorInfo();
            if (id > 0)
            {
                info = _userService.GetUserHealthMonitorInfoById(id);
            }
            ViewBag.userHealthMonitorInfo = info;
            Hashtable uparam = new Hashtable();
            uparam.Add("is_delete", 0);//正常 0 false
            IList<UserInfo> userList = _userService.GetUserInfoList(uparam, "", 0, 500);

            ViewBag.userList = userList;
            return View();
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="LogId"></param>
        /// <param name="UserId"></param>
        /// <param name="HeartBeat"></param>
        /// <param name="Temperature"></param>
        /// <param name="CollectTime"></param>
        public JsonResult ajaxHealthMonitorAccess(int LogId, int UserId, double HeartBeat, double Temperature, string CollectTime)
        {
            UserHealthMonitorInfo info = null;
            ResultInfo result = new ResultInfo();
            result.IsSuccess = false;
            result.Code = 200;
            result.Msg = "操作失败!";
            if (LogId > 0)
            {
                info = _userService.GetUserHealthMonitorInfoById(LogId);
                info.UpdateTime = DateTime.Now;
            }
            else
            {
                info = new UserHealthMonitorInfo();
                info.UpdateTime = DateTime.Now;
                info.CreateTime = DateTime.Now;
            }
            info.UserId = UserId;
            info.HeartBeat = HeartBeat;
            info.Temperature = Temperature;
            info.CollectTime = Convert.ToDateTime(CollectTime);
            if (LogId > 0)
            {
                result.IsSuccess = _userService.UpdateUserHealthMonitorInfo(info);

            }
            else
            {
                LogId = _userService.InsertUserHealthMonitorInfo(info);
                result.IsSuccess = LogId > 0 ? true : false;
            }
            if (result.IsSuccess)
            {
                result.Msg = "成功删除!";
            }
            return Json(result);
        }


        /// <summary>
        /// 随机数生成器
        /// </summary>
        protected static MyRandom rand = new MyRandom();

        /// <summary>
        /// 批量生成
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="generalTaskCount"></param>
        public JsonResult ajaxGeneralData(int userId, int generalTaskCount)
        {
            UserHealthMonitorInfo info = null;
            ResultInfo result = new ResultInfo();
            result.IsSuccess = true;
            result.Code = 200;
            result.Msg = "操作成功!";
            IList<UserHealthMonitorInfo> list = new List<UserHealthMonitorInfo>();
            if (generalTaskCount > 0&& userId>0)
            {
                DateTime temCollectTime = DateTime.Now.AddMinutes(-30);
                for (int i = 0; i < generalTaskCount; i++)
                {
                    UserHealthMonitorInfo addInfo = new UserHealthMonitorInfo();
                    addInfo.CreateTime = DateTime.Now;
                    addInfo.UpdateTime = DateTime.Now;
                    addInfo.UserId = userId;
                    addInfo.HeartBeat = rand.Next(40, 150);
                    addInfo.Temperature = rand.Next(30, 40);
                    addInfo.CollectTime = temCollectTime;
                    list.Add(addInfo);
                    _userService.InsertUserHealthMonitorInfo(addInfo);

                    temCollectTime = temCollectTime.AddMinutes(1);
                }
            }
            return Json(result);
        }
        #endregion



    }
}
